import datetime
from typing import List

from ninja import Router, Query

from apps.commom.user import UserSerializer
from apps.schemas import R
from apps.manager.user_manager.schemas import UserFiltersSchema, VipIdentitySettingsSchema, \
    AgentIdentitySettingsSchema, UsersResponseSchema, OrderFilterByRegionFilterSchema
from models.choices import TransactionStatus, WaterCardType
from models.models import User, VipShip, AgentShip, Goods, OrderInfo, VipOrderInfo, AgentOrderInfo, \
    CustomerServiceFeedbackRecord, WaterCardRecord, WaterCardTransferRecord, VipPackage, AgentPackage
from ninja.pagination import paginate

from django.db.models.aggregates import Sum

from utils.auth import ManagerAuthBearer
from utils.decorators import handle_exception
from utils.paginations import MyPagination

user_manager_router = Router(tags=['用户管理'], auth=ManagerAuthBearer())


def get_day_income():
    """
    获取当日收益
    """
    today = datetime.datetime.today()
    date_zero = datetime.datetime(today.year, today.month, today.day, 0, 0, 0)
    orders = OrderInfo.objects.filter(transaction_time__gt=date_zero,
                                      transaction_status=TransactionStatus.COMPLETED_PAYMENT).values("good_number",
                                                                                                     "good_spec__price")
    vip_orders_pay_sum = VipOrderInfo.objects.filter(transaction_time__gt=date_zero).aggregate(nums=Sum("number"))[
        "nums"]
    agent_orders_pay_sum = AgentOrderInfo.objects.filter(transaction_time__gt=date_zero).aggregate(nums=Sum("number"))[
        "nums"]
    income = 0
    for item in orders:
        income += item["good_number"] * item["good_spec__price"]
    income += vip_orders_pay_sum + agent_orders_pay_sum
    return income


@user_manager_router.post("/index/overview", summary="后台管理系统首页", response=R)
@handle_exception("获取信息失败")
def manage_index(request):
    user_total = User.objects.count()
    good_total = Goods.objects.count()
    order_total = OrderInfo.objects.count() + VipOrderInfo.objects.count() + AgentOrderInfo.objects.count()
    water_card_total = WaterCardRecord.objects.filter(card_type=WaterCardType.GET).aggregate(nums=Sum("number"))["nums"]
    today = datetime.datetime.today()
    date_zero = datetime.datetime(today.year, today.month, today.day, 0, 0, 0)
    today_user = User.objects.filter(creat_time__gt=date_zero).count()
    today_service_feedback = CustomerServiceFeedbackRecord.objects.filter(create_time__gt=date_zero).count()
    today_order_count = OrderInfo.objects.filter(transaction_time__gt=date_zero,
                                                 transaction_status=TransactionStatus.COMPLETED_PAYMENT).count()
    today_vip_order_count = VipOrderInfo.objects.filter(transaction_time__gt=date_zero).count()
    today_agent_order_count = AgentOrderInfo.objects.filter(transaction__gt=date_zero).count()
    today_order = today_order_count + today_agent_order_count + today_vip_order_count
    today_regional = get_day_income()
    result = {
        "user_total": user_total,
        "good_total": good_total,
        "order_total": order_total,
        "water_card_total": water_card_total,
        "today_user": today_user,
        "today_service_feedback": today_service_feedback,
        "today_order": today_order,
        "today_regional": today_regional,
    }

    return R.ok(data=result)


@user_manager_router.get("/users", summary="获取用户列表", response=List[UsersResponseSchema])
@paginate(MyPagination)
@handle_exception("获取用户列表失败")
def get_users(request, filters: UserFiltersSchema = Query(...)):
    """
    获取用户列表
    """
    users = User.objects.all()
    users = filters.filter(users)
    return users


@user_manager_router.get("/user/{user_id}", summary="获取用户信息", response=R)
@handle_exception("获取用户信息失败")
def get_user(request, user_id):
    """
    获取用户信息
    """
    if not user_id:
        return R.fail(msg="user_id is required")
    data = User.objects.get(id=user_id)
    return R.ok(data=UserSerializer(data).data)


@user_manager_router.post("/user_set/vip", summary="设置用户会员身份", response=R)
@handle_exception("设置用户会员身份失败")
def vip_identity_settings(request, data: VipIdentitySettingsSchema):
    """
    设置用户身份
    """
    VipShip.objects.create(user_id=data.user_id, vip_id=data.vip_id, note=data.note)
    user = User.objects.get(id=data.user_id)
    user.user_type = VipPackage.objects.get(pk=data.vip_id)
    user.member_expiration_time = user.member_expiration_time + datetime.timedelta(days=data.day)
    user.save()
    return R.ok(msg="设置成功")


@user_manager_router.post("/user_set/agent", summary="设置用户代理身份", response=R)
@handle_exception("设置用户代理身份失败")
def agent_identity_settings(request, data: AgentIdentitySettingsSchema):
    """
    代理身份设置
    """
    AgentShip.objects.create(user_id=data.user_id, agent_id=data.agent_id, note=data.note)
    user = User.objects.get(id=data.user_id)
    user.agent_type = AgentPackage.objects.get(pk=data.agent_id)
    user.water_card_number = user.water_card_number + data.water_card_number
    user.save()
    WaterCardRecord.objects.create(name="购买水卡", card_type=WaterCardType.GET, number=data.water_card_number,
                                   time=datetime.datetime.now(), user_id=data.user_id)
    return R.ok(msg="设置成功")


@user_manager_router.get("region/income", summary="获取地区收益", response=R)
@handle_exception("获取地区收益失败")
def get_region_income(request, filters: OrderFilterByRegionFilterSchema = Query(...)):
    """
    获取地区收益
    """
    incomes = OrderInfo.objects.filter(transaction_status=TransactionStatus.COMPLETED_PAYMENT). \
        values("good_number", "good_spec__province_agency_income", "good_spec__regional_income")
    water_card_total = OrderInfo.objects.filter(transaction_status=TransactionStatus.COMPLETED_PAYMENT).aggregate(
        nums=Sum("consume_water_card"))["nums"]
    water_card_total = water_card_total if water_card_total else 0
    income_total = 0
    for income in incomes:
        income_total += income["good_number"] * (income["good_spec__province_agency_income"])
        income_total += income["good_number"] * (income["good_spec__regional_income"])
    orders = OrderInfo.objects.filter(transaction_status=TransactionStatus.COMPLETED_PAYMENT)
    orders = filters.filter(orders)
    address = list(set(orders.values_list("address__province_name", "address__city_name", "address__district_name")))
    data = []
    search_income_total = 0
    search_water_card_total = 0
    for addr in address:
        temp_order = orders.filter(address__province_name=addr[0], address__city_name=addr[1],
                                   address__district_name=addr[2]).values_list("good_number",
                                                                               "good_spec__province_agency_income",
                                                                               "good_spec__regional_income",
                                                                               "consume_water_card")
        temp_data = {
            "province": addr[0],
            "city": addr[1],
            "district": addr[2],
        }
        temp_search_income_total = 0
        temp_search_water_card_total = 0
        for item in temp_order:
            temp_search_income_total += item[0] * (item[1])
            temp_search_income_total += item[0] * (item[2])
            search_income_total += temp_search_income_total
            temp_search_water_card_total += item[3]
            search_water_card_total += temp_search_water_card_total
        temp_data["income"] = temp_search_income_total
        temp_data["water_card"] = temp_search_water_card_total
        data.append(temp_data)
    result = {
        "income_total": income_total,
        "water_card_total": water_card_total,
        "search_income_total": search_income_total,
        "search_water_card_total": search_water_card_total,
        "items": data
    }
    return R.ok(data=result)
